<template>
  <div :class="className" :style="{ height: height, width: width }" />
</template>

<script>
import * as echarts from 'echarts'
require('echarts/theme/macarons') // echarts theme
import resize from './mixins/resize'
import { getRescueCountPie } from '@/api/shop/charts'
const animationDuration = 3000

export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '300px'
    }
  },
  data() {
    return {
      chart: null,
      data: []
    }
  },
  mounted() {
    this.initChart();

    // this.getOrderCountPie()

    this.$nextTick(() => {
      this.fetchDataAndUpdateChart();
    })
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$el, 'macarons', {
        width: 300,
        height: 200
      });
    },
    updateChart() {
      if (!this.chart) return;

      // 将观察者对象转换为普通对象
      const chartData = this.data.map(item => ({
        name: item.name,
        value: item.value
      }));

      const option = {
        tooltip: {
          trigger: 'item'
        },
        legend: {
          orient: 'vertical',
          right: 40,
          top: 'center'
        },
        series: [
          {
            name: 'Access From',
            type: 'pie',
            radius: ['40%', '70%'],
            avoidLabelOverlap: false,
            center: ['25%', '50%'],
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: 40,
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: chartData
          }
        ]
      };
      this.chart.setOption(option);
    },
    fetchDataAndUpdateChart() {
      getRescueCountPie().then(response => {
        this.data = response.data;
        this.updateChart();
      }).catch(error => {
        console.error("Failed to fetch data:", error);
      });
    }
  }
}

</script>
